package com.itheima.itheima_health.service.Impl;

import com.itheima.itheima_health.constant.MessageConstant;
import com.itheima.itheima_health.constant.RedisConstant;
import com.itheima.itheima_health.exception.BaseException;
import com.itheima.itheima_health.mapper.UserLoginMapper;
import com.itheima.itheima_health.pojo.Login;
import com.itheima.itheima_health.pojo.User;
import com.itheima.itheima_health.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements UserLoginService {
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public User userlogin(Login loginInfo) {
        User user = userLoginMapper.getByEmail(loginInfo);
        Object orediscode = redisTemplate.opsForSet().randomMember(loginInfo.getEmail() + RedisConstant.EMAIL_CODE_KEY);
        if (user==null){
            log.info("邮箱错误");
            throw new BaseException(MessageConstant.LOGIN_EMAIL_FAIL1);
        } else if (orediscode==null || (!loginInfo.getCode().equals(orediscode))){
            //验证码无效
            log.info("验证码无效");
            throw new BaseException(MessageConstant.LOGIN_CODE_FAIL1);
        } else {
            redisTemplate.delete(loginInfo.getEmail() + RedisConstant.EMAIL_CODE_KEY);
            log.info("登录成功");
            return user;
        }
    }
}
